package com.doublefish.doublefishrobot.ui.home.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者:dugaofeng on 2024/10/18 16:32
 */
public class ModeSettingItemValuePopView extends Dialog {

    private Context mContext;

    private List<ModeSettingBean.ModeSettingItemBean> itemBeans;  //传进来的数据
    private List<String> itemMsgs;
    private List<ModeSettingBean.ModeSettingItemBean> tmpItemBeans;  //操作中的临时数据

    private int index= 0;
    private ModeSettingBean.ModeSettingItemBean itemBean;  //当前的数据
    private String itemMsg;
    private ModeSettingBean.ModeSettingItemBean tmpItemBean;  //操作中的临时数据

    private ModeSettingItemValuePopView.OnSettingItemValuePopViewListner listener;

    private TitleSegmentView titleSegmentView;
    private TextView titleTv;
    private TextView msgTv;

    private LinearLayout segmentLL;
    private ModeValueRangeSegmentView segmentView;

    private LinearLayout fixedLL;
    private ModeSettingItemValueView itemValueView;
    private ModeSettingItemSlider fixedValueSlier;
    private ModeSettingItemDoubleSlider rangeValueSlier;

    private LinearLayout rangeLL;
    private ModeSettingItemValueView minItemValueView;
    private ModeSettingItemValueView maxItemValueView;

    private TextView okTv;
    private TextView cancelTv;

    //    由于下面的滑块滑动是需要获取到可以滑动的宽度
//    这里做一个辅助的LinearLayout，专门计算 这个 宽度
    private View v1;
    private View v2;


    public ModeSettingItemValuePopView(Context context, ModeSettingBean.ModeSettingItemBean itemBean, String itemMsg, ModeSettingItemValuePopView.OnSettingItemValuePopViewListner listener) {
        super(context, R.style.dialog);

        this.mContext = context;
        this.itemBean = itemBean;
        this.itemMsg = itemMsg;
        this.listener = listener;

        this.tmpItemBean = new ModeSettingBean.ModeSettingItemBean(itemBean.getName(), itemBean.isCanChooseRange(), itemBean.isChooseRange(), itemBean.getMaxValue(), itemBean.getMinValue(), itemBean.getCurrentValue(), itemBean.getCurrentMaxValue(), itemBean.getCurrentMinValue());
    }

    public ModeSettingItemValuePopView(Context context,List<ModeSettingBean.ModeSettingItemBean> itemBeans, List<String> itemMsgs, int index, ModeSettingItemValuePopView.OnSettingItemValuePopViewListner listener) {
        super(context, R.style.dialog);

        this.mContext = context;
        this.itemBeans = itemBeans;
        this.itemMsgs = itemMsgs;
        this.listener = listener;

        if (itemBeans != null && itemBeans.size() > 0) {
           tmpItemBeans = new ArrayList<>();
            for (int i = 0; i < itemBeans.size(); i++) {
                ModeSettingBean.ModeSettingItemBean tmp = new ModeSettingBean.ModeSettingItemBean(itemBeans.get(i).getName(), itemBeans.get(i).isCanChooseRange(), itemBeans.get(i).isChooseRange(), itemBeans.get(i).getMaxValue(), itemBeans.get(i).getMinValue(), itemBeans.get(i).getCurrentValue(), itemBeans.get(i).getCurrentMaxValue(), itemBeans.get(i).getCurrentMinValue());
                tmpItemBeans.add(tmp);
            }
            this.index = index;
            this.itemBean = itemBeans.get(index);
            this.itemMsg = itemMsgs.get(index);
            this.tmpItemBean = tmpItemBeans.get(index);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_mode_setting_item_value);
        setCanceledOnTouchOutside(false);
        initView();
        initListner();

        relaodData();
    }

    private void initView() {
        titleSegmentView = findViewById(R.id.title_segment);
        if (itemBeans != null && itemBeans.size() > 0) {
            titleSegmentView.setVisibility(View.VISIBLE);
            titleSegmentView.setTitles(index, itemBeans);
        }

        titleTv = findViewById(R.id.tv_title);
        msgTv = findViewById(R.id.tv_msg);

        segmentLL = findViewById(R.id.ll_segment);
        segmentView = findViewById(R.id.segment);

        fixedLL = findViewById(R.id.ll_fixed);
        itemValueView = findViewById(R.id.itemvalue0);
        fixedValueSlier = findViewById(R.id.slider_fixed);

        rangeLL = findViewById(R.id.ll_range);
        minItemValueView = findViewById(R.id.itemvalue1);
        maxItemValueView = findViewById(R.id.itemvalue2);
        rangeValueSlier = findViewById(R.id.slider_range);

        okTv = findViewById(R.id.tv_ok);
        cancelTv = findViewById(R.id.tv_cancel);

        //辅助 计算 可滑动的宽度
        v1 = findViewById(R.id.view_1);
        v2 = findViewById(R.id.view_2);
    }

    private void relaodData() {
        titleTv.setText(itemBean.getName());
        msgTv.setText(itemMsg == null ? "" : itemMsg);

        //0.固定值  1.最大值  2.最小值
        minItemValueView.setType(2);
        minItemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getCurrentMinValue());
        maxItemValueView.setType(1);
        maxItemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getCurrentMaxValue());

        itemValueView.setType(0);
        itemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getCurrentValue());

        fixedValueSlier.setValue(tmpItemBean.getCurrentValue(), tmpItemBean.getMinValue(), tmpItemBean.getMaxValue());
        rangeValueSlier.setValue(tmpItemBean.getCurrentMinValue(), tmpItemBean.getCurrentMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getMaxValue());

        updateViewVisibility();
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        //计算 可滑动的宽度
        int maxWidth = v1.getMeasuredWidth() - v2.getMeasuredWidth();
        rangeValueSlier.setMaxWidth(maxWidth);
        fixedValueSlier.setMaxWidth(maxWidth);
    }

    private void updateViewVisibility() {
        segmentView.setIndex(tmpItemBean.isChooseRange() ? 1 : 0);
        if (tmpItemBean.isCanChooseRange()) {
            segmentLL.setVisibility(View.VISIBLE);

            if (tmpItemBean.isChooseRange()) {
                fixedLL.setVisibility(View.GONE);
                rangeLL.setVisibility(View.VISIBLE);
                fixedValueSlier.setVisibility(View.GONE);
                rangeValueSlier.setVisibility(View.VISIBLE);
            } else {
                fixedLL.setVisibility(View.VISIBLE);
                rangeLL.setVisibility(View.GONE);
                fixedValueSlier.setVisibility(View.VISIBLE);
                rangeValueSlier.setVisibility(View.GONE);
            }
        } else {
            segmentLL.setVisibility(View.GONE);

            fixedLL.setVisibility(View.VISIBLE);
            rangeLL.setVisibility(View.GONE);
            fixedValueSlier.setVisibility(View.VISIBLE);
            rangeValueSlier.setVisibility(View.GONE);
        }
    }

    private void initListner() {
        titleSegmentView.setOnTitleSegmentListner(new OnTitleSegmentListner() {
            @Override
            public void onSelect(int index1) {
                index = index1;
                itemBean = itemBeans.get(index);
                itemMsg = itemMsgs.get(index);
                tmpItemBean = tmpItemBeans.get(index);
                relaodData();
            }
        });

        segmentView.setOnModeValueRangeSegmentViewItemChangedListner(new ModeValueRangeSegmentView.OnModeValueRangeSegmentViewItemChangedListner() {
            @Override
            public void onModeValueRangeSegmentViewItemChanged(int index) {
                tmpItemBean.setChooseRange(index == 1);
                updateViewVisibility();
            }
        });
        //type  0.固定值  1.最大值  2.最小值
        itemValueView.setOnModeSettingItemValueViewListner(new ModeSettingItemValueView.OnModeSettingItemValueViewListner() {
            @Override
            public void onItemValueChanged(int type, int currentValue) {
                tmpItemBean.setCurrentValue(currentValue);
                fixedValueSlier.setValue(currentValue, tmpItemBean.getMinValue(), tmpItemBean.getMaxValue());
            }
        });
        minItemValueView.setOnModeSettingItemValueViewListner(new ModeSettingItemValueView.OnModeSettingItemValueViewListner() {
            @Override
            public void onItemValueChanged(int type, int currentValue) {
                tmpItemBean.setCurrentMinValue(currentValue);
                rangeValueSlier.setValue(currentValue, tmpItemBean.getCurrentMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getMaxValue());
                maxItemValueView.updateMinValue(currentValue);
            }
        });
        maxItemValueView.setOnModeSettingItemValueViewListner(new ModeSettingItemValueView.OnModeSettingItemValueViewListner() {
            @Override
            public void onItemValueChanged(int type, int currentValue) {
                tmpItemBean.setCurrentMaxValue(currentValue);
                rangeValueSlier.setValue(tmpItemBean.getCurrentMinValue(), currentValue, tmpItemBean.getMinValue(), tmpItemBean.getMaxValue());
                minItemValueView.updateMaxValue(currentValue);
            }
        });

        fixedValueSlier.setOnModeSettingItemSliderListner(new ModeSettingItemSlider.OnModeSettingItemSliderListner() {
            @Override
            public void onValueChanged(int cur) {
                tmpItemBean.setCurrentValue(cur);
                itemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), cur);
            }
        });

        rangeValueSlier.setOnModeSettingItemDoubleSliderListner(new ModeSettingItemDoubleSlider.OnModeSettingItemDoubleSliderListner() {
            @Override
            public void onValueChanged(int curMin, int curMax) {
                tmpItemBean.setCurrentMinValue(curMin);
                tmpItemBean.setCurrentMaxValue(curMax);

//                minItemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getCurrentMinValue());
//                maxItemValueView.setValue(tmpItemBean.getMaxValue(), tmpItemBean.getMinValue(), tmpItemBean.getCurrentMaxValue());
                minItemValueView.setValue(curMax, tmpItemBean.getMinValue(), curMin);
                maxItemValueView.setValue(tmpItemBean.getMaxValue(), curMin, curMax);
            }
        });

        okTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                clearAllEditetextFocus();

                if (tmpItemBean.isChooseRange()) {
                    if (tmpItemBean.getCurrentMinValue() > tmpItemBean.getCurrentMaxValue()) {
                        if (listener != null) {
                            listener.onValueError(getContext().getString(R.string.max_greater_min));
                        }
                        return;
                    }
                    itemBean.setCurrentMinValue(tmpItemBean.getCurrentMinValue());
                    itemBean.setCurrentMaxValue(tmpItemBean.getCurrentMaxValue());
                } else {
                    itemBean.setCurrentValue(tmpItemBean.getCurrentValue());
                }
                itemBean.setChooseRange(tmpItemBean.isChooseRange());
                if (listener != null) {
                    listener.onValueFinish(itemBean, index);
                }
                dismiss();
            }
        });

        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onCancelBtnClick();
                }
                hideKeyboard();
                dismiss();
            }
        });
    }

    //回收键盘
    private void hideKeyboard() {
        //回收键盘
        InputMethodManager imManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imManager != null && getCurrentFocus() != null) {
            imManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    private void clearAllEditetextFocus() {
        itemValueView.clearFocus();
        minItemValueView.clearFocus();
        maxItemValueView.clearFocus();
    }

    public static class TitleSegmentView extends LinearLayout {
        private Context mContext;
        private TextView curTv;

        private OnTitleSegmentListner onTitleSegmentListner;

        public TitleSegmentView(@NonNull Context context) {
            this(context, null);
        }

        public TitleSegmentView(@NonNull Context context, @Nullable AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public TitleSegmentView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            this.mContext = context;
            initView();
        }

        private void initView() {
            setOrientation(HORIZONTAL);
        }

        public void setOnTitleSegmentListner(OnTitleSegmentListner onTitleSegmentListner) {
            this.onTitleSegmentListner = onTitleSegmentListner;
        }

        @SuppressLint("ResourceType")
        public void setTitles(int index, List<ModeSettingBean.ModeSettingItemBean> itemBeans) {
            for (int i = 0; i < itemBeans.size(); i++) {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1);
                TextView textView = new TextView(mContext);
                textView.setText(itemBeans.get(i).getName());
                textView.setGravity(Gravity.CENTER);
                textView.setTextColor(ContextCompat.getColorStateList(mContext, R.drawable.selector_textcolor_white_black));
                if (i == 0) {
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shap_lefttop_leftbottom));
                } else if (i == itemBeans.size() - 1) {
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shap_righttop_rightbottom));
                } else {
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_rectangle));
                }
                addView(textView, layoutParams);

                int finalI = i;
                textView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickItem(textView, finalI);
                    }
                });
                if (index == i) {
                    textView.setSelected(true);
                    curTv = textView;
                }
            }
        }

        private void onClickItem(TextView view,int index) {
            if (view == curTv) {
                return;
            }
            curTv.setSelected(false);
            view.setSelected(true);
            curTv = view;

            if (onTitleSegmentListner != null) {
                onTitleSegmentListner.onSelect(index);
            }
        }
    }

    //region OnSettingItemValuePopViewListner
    public interface OnSettingItemValuePopViewListner {
        void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index);

        void onValueError(String error);

        void onCancelBtnClick();
    }

    interface OnTitleSegmentListner {
        void onSelect(int index);
    }

    //endregion
}